<template>
	<div class="rukuInfo">
		<div class="twoStageWindow" style="overflow:hidden">
			<div class="twoStageWindowTitle">
				<span style="position: absolute;left: 10px;">
					{{status=="rukudengji"?"入库登记":(status=="rukutijiao"?"入库修改":"查看详情")}}
				</span>
				<div class="twoStageWindowClose">
					<el-button v-if="status=='rukudengji'||status=='rukutijiao'" size="mini" type="primary" v-on:click="doSbumit(1)" :disabled="!isRepeat">提交</el-button>
					<el-button v-if="status=='rukudengji'||status=='rukutijiao'" size="mini" type="primary" v-on:click="doSbumit(0)" :disabled="!isRepeat">保存</el-button>
					<el-button v-if="status=='rukushenpi'" size="mini" type="primary" v-on:click="close">通过</el-button>
					<el-button v-if="status=='rukushenpi'" size="mini" type="primary" v-on:click="close">驳回</el-button>
					<el-button size="mini" v-on:click="close">关闭</el-button>
				</div>
			</div>
			<div class="containercontent" style="margin-top:40px;height:calc(100% - 40px);padding-top: 0;">
				<el-form label-width="110px" :inline="false" class="demo-form-inline rukuForm" :model="instockParams" :rules="rules" ref="rukuForm">
					<el-form-item label="单据号" prop='billNo' v-if="status != 'rukudengji'">
						<el-col :span="22">
							<el-input size="mini" placeholder="系统生成" disabled v-model="instockParams.billNo"></el-input>
						</el-col>
					</el-form-item>
					<el-form-item label="创建人" v-if="status != 'rukudengji'">
						<el-col :span="22">
							<el-select disabled v-model="instockParams.createBy" clearable placeholder="请选择" size="mini" filterable style="width:100%;">
								<el-option v-for="item in EmployeeByLabs" :key="item.account" :label="item.name" :value="item.account"  :disabled="item.disabled">
								</el-option>
							</el-select>
						</el-col>
					</el-form-item>

					<el-form-item label="入库日期" prop='billdate'>
						<el-col :span="22">
							<el-date-picker :disabled="shenpi" size="mini" style="width:100%;" v-model="instockParams.billdate" value-format="yyyy-MM-dd" type="date" :picker-options="pickerOptions" placeholder="选择入库日期">
							</el-date-picker>
						</el-col>
					</el-form-item>
					<el-form-item label="登记人" prop='storekeeper'>
						<el-col :span="22">
							<el-select :disabled="shenpi" v-model="instockParams.storekeeper" clearable placeholder="请选择" size="mini" filterable style="width:100%;">
								<el-option v-for="item in EmployeeByLabs" :key="item.account" :label="item.name" :value="item.account"  :disabled="item.disabled">
								</el-option>
							</el-select>
						</el-col>
					</el-form-item>
          <el-form-item label="来源" prop='source'>
          	<el-col :span="22">
          		<el-input size="mini" placeholder="货单编号等" :disabled="shenpi"  v-model="instockParams.source" style="width:100%;"></el-input>
          	</el-col>
          </el-form-item>
					<el-form-item label="备注" prop='remark'  class="remark">
						<el-col :span="22">
							<el-input   placeholder="备注" size="mini" :disabled="shenpi" v-model="instockParams.remark">
							</el-input>
						</el-col>
					</el-form-item>
				</el-form>
				<div class="elTab">
					<el-tabs>
						<el-tab-pane label="物资列表">
							<div style="float:right;margin-bottom:5px;">
								<el-button v-if="!shenpi" type="primary" size="mini" @click="xuanzewuziShow=true">选择物资</el-button>
							</div>
							<el-table :data="instockParams.instockdetBeanList" size='mini' :height='TableHeight'>
								<el-table-column fixed label="序号" min-width="50px">
									<template slot-scope="scope">
										{{scope.$index+1}}
									</template>
								</el-table-column>
								<el-table-column prop="certificateNumber" min-width="120" label="证书序号" fixed>
									<template slot-scope="scope">
										<el-input size="mini" v-model="scope.row.certificateNumber" :disabled="shenpi" :title = "scope.row.certificateNumber"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="number" min-width="120" label="物资编号" fixed>
									<template slot-scope="scope">
										<el-input size="mini" v-model="scope.row.number" placeholder="CAS号或其他" :disabled="shenpi" :title = "scope.row.number"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="name" label="物资名称" min-width="120" fixed>
									<template slot-scope="scope">
										<span v-if="scope.row.name">
											{{scope.row.name}}
										</span>
										<span v-if="scope.row.materialName">
											{{scope.row.materialName}}
										</span>
										<el-input size="mini" v-if="scope.row.new" v-model="scope.row.name"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="materialTypeName" label="物资类型" min-width="110" fixed show-overflow-tooltip>
									<template slot-scope="scope">
										<span v-if="!scope.row.new">
											{{scope.row.materialTypeName}}
										</span>
										<el-cascader :disabled="shenpi" v-if="scope.row.new" expand-trigger="hover" :options="options" v-model="scope.row.materialTypeName" size="mini" style="width:100%;">
										</el-cascader>
									</template>
								</el-table-column>
								<el-table-column prop="batch" min-width="100" label="批号">
									<template slot-scope="scope">
										<el-input size="mini" v-model="scope.row.batch" :disabled="shenpi"  :title = "scope.row.batch"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="purity" label="标准值" width="90">
									<template slot-scope="scope">
										<el-autocomplete class="inline-input" size="mini" :title = "scope.row.purity" v-model="scope.row.purity" :fetch-suggestions="(queryString, cb) => querySearch(queryString, cb,scope.row)" @select="(val) => handleSelect(val,scope.row)" :disabled="shenpi||scope.row.standardSample=='1'" ></el-autocomplete>
									</template>
								</el-table-column>
								<el-table-column prop="concentration" label="不确定值" width="90">
									<template slot-scope="scope">
										<el-autocomplete class="inline-input" size="mini" :title = "scope.row.concentration" v-model="scope.row.concentration" :fetch-suggestions="(queryString, cb) => querySearch1(queryString, cb,scope.row)" @select="(val) => handleSelect1(val,scope.row)" :disabled="shenpi||scope.row.standardSample=='1'"></el-autocomplete>
									</template>
								</el-table-column>
								<el-table-column prop="youxiaoqi" label="有效期" width="150">
									<template slot-scope="scope">
										<el-date-picker style="width: 100%;" :disabled="shenpi" size="mini" v-model="scope.row.validitydate" value-format="yyyy-MM-dd" type="date" :picker-options="pickerOptions1">
										</el-date-picker>
									</template>
								</el-table-column>
								<el-table-column label="存放位置" width="100">
									<template slot-scope="scope">
										<el-autocomplete class="inline-input" size="mini" v-model="scope.row.stockCode"  :title = "scope.row.stockCode" :fetch-suggestions="querySearch2" :disabled="shenpi">
										</el-autocomplete>
									</template>
								</el-table-column>
								<el-table-column prop="qty" width="100" label="数量">
									<template slot-scope="scope">
										<el-input size="mini" v-model="scope.row.qty" :min="1" :disabled="shenpi" oninput="this.value=this.value.replace(/[^0-9.]+/,'');"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="internalNumber" min-width="100" label="内部编号">
									<template slot-scope="scope">
										<el-input size="mini" v-model="scope.row.internalNumber" :disabled="shenpi"  :title = "scope.row.internalNumber"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="baozhuangguige" label="物资规格" width="100">
									<template slot-scope="scope">
										<el-input size="mini" v-model="scope.row.spce" :disabled="shenpi" ></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="medium" label="介质" width="100">
									<template slot-scope="scope">
										<el-input size="mini" v-model="scope.row.medium" :disabled="shenpi" :title = "scope.row.medium"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="fixedValueDate" label="定值日期" width="150">
									<template slot-scope="scope">
										<el-date-picker style="width: 100%;" :disabled="shenpi" size="mini" v-model="scope.row.fixedValueDate" value-format="yyyy-MM-dd" type="date">
										</el-date-picker>
									</template>
								</el-table-column>
								<el-table-column label="生产厂家" min-width="200">
									<template slot-scope="scope">
										<el-select :disabled="shenpi" v-model="scope.row.companyCode" size="mini" filterable clearable>
											<!--被删除或者停用的不可选中-->
											<el-option v-for="item in supplierData" :key="item.id" :label="item.name" :value="item.id" :disabled = "item.status == 0 || item.deleteFlag">
											</el-option>
										</el-select>
									</template>
								</el-table-column>
								<el-table-column prop="storageTemperature" label="保存温度" width="100">
									<template slot-scope="scope">
										<el-input size="mini" v-model="scope.row.storageTemperature" :disabled="shenpi" :title="scope.row.storageTemperature"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="unit" label="单位" width="100">
									<template slot-scope="scope">
										<el-input size="mini" v-model="scope.row.unit" :disabled="shenpi" :title = "scope.row.unit"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="remark" label="备注" width="100">
									<template slot-scope="scope">
										<el-input size="mini" v-model="scope.row.remark" :disabled="shenpi" :title = "scope.row.remark"></el-input>
									</template>
								</el-table-column>
								<el-table-column label="操作" min-width="180"  :key="Math.random()">
									<template slot-scope="scope">
										<el-button type="text" size="mini" @click="deleteWuZi(scope.$index)" v-if="status!='chakanruku'">删除</el-button>
										<el-button type="text" size="mini" @click="sampleSet(scope.row,'edit')" v-if="scope.row.standardSample=='1' && status != 'chakanruku'">标样设置</el-button>
										<el-button type="text" size="mini" @click="sampleSet(scope.row,'look')" v-if="status == 'chakanruku'" :disabled = "scope.row.standardSample!='1'">标样详情</el-button>
                    					<el-button type="text" size="mini" @click="fileDialog(scope.row)" >附件</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-tab-pane>
					</el-tabs>
				</div>
			</div>
		</div>
		<div v-if="xuanzewuziShow">
			<xuanzewuzi></xuanzewuzi>
		</div>
		<div v-if="qualitySampleAddShow">
			<quality-sample-add :bjorck="bjorck" :selectRow.sync="selectRow" :samplesetObj.sync="samplesetObj"></quality-sample-add>
		</div>
    <files :addVisible.sync='fileShow' :selectRow.sync="selectRow" :shenpi="shenpi"></files>
	</div>
</template>

<script>
import { mapState } from 'vuex'
import xuanzewuzi from './children/xuanzewuzi.vue'
import files from './children/files.vue'
import qualitySampleAdd from '../../qualityControl/qualityControl/children/qualitySampleAdd.vue'


export default {
	data() {
		return {
			pickerOptions: {
				disabledDate(time) {
					return time.getTime() > Date.now();
				},
			},
			saveType: '',
			qualitySampleAddShow: false,
			bjorck: '',
			xuanzewuziShow: false,
			options: [],
			selectRow: [],
			samplesetObj: {},
			stockComList: [],
			isRepeat: true,
			rules: {
				storekeeper: [
					{ required: true, trigger: 'change', message: "请选择登记人" },
				],
        // source:[
        //   { required: true, trigger: 'blur', message: "请输入来源" },
        // ]
			},
			instockdetList: [], //选择物资浓度和纯度的列表
			pickerOptions1: { // 只能选择今天之前
				disabledDate(time) {
					return time.getTime() < Date.now() - 8.64e7 ;//如果没有后面的-8.64e6就是不可以选择今天的
				}
			},
      supplierData:[],
      rukuOrChuku:"ruku",
      fileShow:false,
		}
	},
	props: ['status', 'shenpi', 'instockParams'],
	components: {
		xuanzewuzi, qualitySampleAdd,files
	},
	computed: {
		...mapState(['enableStatus', 'typeofAbilityTableDate', 'materialType', 'EmployeeByLabs']),
		TableHeight() {
			return ((window.innerHeight - 180) - 250)
		}
	},
	created() {
		this.saveType = this.status;
	},
	mounted() {
		this.readStockComList();
		this.init();
	},
	watch: {
      'selectRow.number'(val){
        console.log(val)
        delete this.selectRow.fileList
      },
      'selectRow.batch'(val){
        console.log(val)
        delete this.selectRow.fileList
      }
	},
	methods: {
		init() {
			this.$http({
				apiUrl: 'resource/readSupplierComboList.htm',
				method: 'post',
				params: '',
				isJson: false
			}).then(res=>{
				if(res.code == 0) {
					this.supplierData = res.data
				}
			})
		},
		// 鼠标聚焦 调用浓度和纯度
		readInstockdetList(row) {
			return new Promise((resolve, reject) => {
				this.$http({
					apiUrl: '/resource/readInstockdetList.htm',
					method: 'post',
					params: { materialCode: row.materialCode },
					isJson: true
				}).then(res => {
					if (res.code === 0) {
						resolve(res)
					}
				})
			})
		},
		// 选中纯度后
		handleSelect(val, row) {
			row.concentration = val.concentration;

		},
		querySearch(queryString, cb, row) {
			this.readInstockdetList(row).then(res => {
				var restaurants = [];
				for (var i in res.data) {
					if (res.data[i].purity != undefined) {
						restaurants.push(res.data[i])
						this.$set(res.data[i], 'value', res.data[i].purity)
					}
				}
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				// 调用 callback 返回建议列表的数据
				cb(results);
			})
		},
		createFilter(queryString) {
			return (restaurant) => {
				return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
			};
		},
		handleSelect1(val, row) {
			row.purity = val.purity;
		},
		querySearch1(queryString, cb, row) {
			this.readInstockdetList(row).then(res => {
				var restaurants = [];
				for (var i in res.data) {
					if (res.data[i].concentration != undefined && res.data[i].concentration != '') {
						restaurants.push(res.data[i])
						this.$set(res.data[i], 'value', res.data[i].concentration)
					}

				}
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				// 调用 callback 返回建议列表的数据
				cb(results);
			})
		},
		// 仓库
		querySearch2(queryString, cb, ) {
			this.readStockComList().then(res => {
				for (var i in res.data) {
					res.data[i].value = res.data[i].name
				}
				var restaurants = res.data;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				// 调用 callback 返回建议列表的数据
				cb(results);
			})
		},
		supplierChange(val) {
			let arr = this.supplierData.filter(item =>
				item.id == val
			)
			this.instockParams.supplierName = arr[0].name
		},
		//			/system/readStockComList.htm获取存储位置接口
		readStockComList() {
			return new Promise((resolve, reject) => {
				this.$http({
					apiUrl: '/system/readStockComList.htm',
					method: 'post',
				}).then(res => {
					if (res.code === 0) {
						resolve(res)
					}
				})
			})
		},
		//			2、(1)交互名称：入库登记
		doSbumit(code) {

			this.$refs['rukuForm'].validate((valid) => {
				if (valid) {

					let url;
					this.instockParams.submitType = code;
					if (this.instockParams.instockdetBeanList.length == 0) {
						this.$notify({
							showClose: true,
							message: '请添加入库物资',
							type: 'warning',
							title:"警告"
						})
						return
					}
					// let set1 = new Set() //判断是否有重复批号和编号的
					// for(var i in this.instockParams.instockdetBeanList){
					// 	var numberBatch = this.instockParams.instockdetBeanList[i].number + this.instockParams.instockdetBeanList[i].batch;
					// 	set1.add(numberBatch)
					// }
					// if(set1.size !== this.instockParams.instockdetBeanList.length){
					// 	this.$notify({
					// 		showClose: true,
					// 		message: '物资批号与物资编号不能同时相同!',
					// 		type: 'warning',
					// 		title:"警告"
					// 	})
					// 	return;
					// }

					if (this.saveType == 'rukudengji') {
						url = 'resource/addInstock.htm'
						for (let item of this.instockParams.instockdetBeanList) {
							if (!item.hasOwnProperty('itemStandardList')) {
								item.itemStandardList = []
							}
						}
					} else if (this.saveType == 'rukutijiao') {

						url = 'resource/updateInstock.htm'
					}

					this.isRepeat = false;
					this.$http({
						apiUrl: url,
						method: 'post',
						params: this.instockParams
					}).then(res => {
						this.isRepeat = true;
						if (res.code === 0) {
							if (code == 0) {
								this.$notify({
									showClose: true,
									message: '保存成功！',
									type: 'success',
									title: "成功"

								})
                if(this.saveType == 'rukudengji'){
                   this.instockParams.id = res.data.id; //如果是保存的话 把返回的id重新赋值给这条数据
                   this.instockParams.billNo = res.data.billNo;
                }

								this.saveType = 'rukutijiao'
                if(this.instockParams.instockdetBeanList.length > 0){ //上传附件
                var that = this;
                  this.instockParams.instockdetBeanList.forEach(async(item,index) =>{

                    if(item.fileList.length >0){
                      await that.upload(item)
                    }
                  })

                }
							} else {
								this.$notify({
									showClose: true,
									message: '提交成功！',
									type: 'success',
									title: "成功"
								})
								this.close()

							}
							this.$parent.readInstockList()

						}
					})
				} else {

				}
			})

		},
    async upload(item) {
      var formData = new FormData();
      item.fileList.forEach((item1) =>{
        formData.append('file',item1)
      })
      formData.append('type', 3) //3是附件的意思
      formData.append('taskType', null)
      formData.append('detectability', null)
      formData.append('fileType', 'inStock')
      formData.append('ids',item.number+item.batch)
      let res = await this.$axios({
        method: 'post',
        url: '/download/fileUpload.htm',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
          'token':sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
         }
      })
      // .then((res) =>{
        var data = res.data
          event.target.value= "";
         if (data.code == 0) {
           // this.$notify({
           //   title: '消息',
           //   message: '上传成功',
           //   type: 'success'
           // })
           // this.getFilePathByIds();
         } else {
        //    this.$notify({
            			// 		title: '消息',
            			// 		message: '上传失败',
            			// 		type: "warning"
            			// })
         }
      // }).catch(() =>{

      // })


    },
		//			5、(1)交互名称：修改入库登记
		updateInstock(code) {
			this.instockParams.submitType = code;
			for (let i of this.instockParams.instockdetBeanList) {
				i.materialCode = i.code || i.materialCode
				i.materialName = i.name || i.materialName
				i.materialNumber = i.materialType || i.materialNumber
			}
			this.$http({
				apiUrl: 'resource/updateInstock.htm',
				method: 'post',
				params: this.instockParams
			}).then(res => {
				if (res.code === 0) {
					if (code == 0) {
						this.$message({
							showClose: true,
							message: '修改保存成功！',
							type: 'success'
						})
					} else {
						this.$message({
							showClose: true,
							message: '修改提交成功！',
							type: 'success'
						})
						this.close()
					}

					this.$parent.readInstockList()
				}
			})

		},

		deleteWuZi(index) {
			this.instockParams.instockdetBeanList.splice(index, 1);
		},
		close() {
			this.$parent.rukudengjiShow = false
			this.isRepeat = true;
		},
		sampleSet(row, flag) {
			this.selectRow = row
			if (!this.selectRow.hasOwnProperty('itemStandardList')) {
				this.selectRow.itemStandardList = []
			}
			this.readSampleSet(row)
			this.bjorck = flag

		},
		//			3、(1)交互名称：获取标样设置列表
		// 			(2)url:readSampleSet.htm
		readSampleSet(row) {
			console.log(row)
			this.$http({
				apiUrl: 'resource/readSampleSet.htm',
				method: 'post',
				params: {
					number: row.number,
					batch: row.batch
				},
				isJson: false
			}).then(res => {
				if (res.code === 0) {
					if (this.selectRow.itemStandardList.length == 0) {
						for (var i in res.data) {
							this.selectRow.itemStandardList.push(res.data[i])
						}
					}

					this.qualitySampleAddShow = true;
				}
			})
		},
    fileDialog(row){
      if(!row.number || !row.batch){
        this.$notify({
          title: '消息',
          message: '请输入完整的物资编号和物资批号！',
          type: 'warning'
        })
        return;
      }
      this.selectRow = row
      if (!this.selectRow.hasOwnProperty('fileList')) {
      	this.getFilePathByIds(row)
      }else{
        this.fileShow = true;
      }


    },
    getFilePathByIds(item) {
       this.$http({
         method: 'post',
         apiUrl: '/download/getFilePathByIds.htm',
         params: { ids: item.number+item.batch },
         isJson: false,
       }).then(res => {
         if (res.code == 0) {
           if (res.data.length >0){
             this.selectRow.fileList = res.data

           }
           this.fileShow = true;
         }

       })
     },
	}
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
	-webkit-appearance: none;
}

input[type="number"] {
	-moz-appearance: textfield;
}

.containercontent .width73 {
	width: 73px;
}

.rukuForm .el-form-item {
	width: 49%;
	display: inline-block;
	margin-bottom: 15px;
}



.rukuForm {
		height: 180px;
	}

.rukuInfo .elTab {
	padding: 0 20px;
	height:calc(100% - 180px)
}

.rukuInfo .elTab .el-tabs {
	height: 100%;
}

/* .rukuInfo .remark .el-form-item__content {
	width: calc(100% - 80px);
} */

.rukuInfo .el-autocomplete-suggestion li {
	padding: 0 5px !important;
}
</style>
